package demo.command;

/**
 * @author zheng9feng
 * @date 2021/5/10 12:43
 * jstack:生成虚拟机当前时刻的线程快照    Stack Trace for Java
 * （Stack Trace for Java）命令用于生成虚拟机当前时刻的线程快照。线程快照就是当前虚拟机内每一条线程正在执行的方法堆栈的集合.
 * 生成线程快照的目的主要是定位线程长时间出现停顿的原因，如线程间死锁、死循环、请求外部资源导致的长时间等待等都是导致线程长时间停顿的原因。
 * 线程出现停顿的时候通过jstack来查看各个线程的调用堆栈，就可以知道没有响应的线程到底在后台做些什么事情，或者在等待些什么资源
 * jstack
 * Usage:
 * jstack [-l][-e] <pid>
 * (to connect to running process)
 * <p>
 * Options:
 * -l  long listing. Prints additional information about locks
 * -e  extended listing. Prints additional information about threads
 * -? -h --help -help to print this help message
 */
public class DeadLockDemo {
	//资源 1
	private static Object resource1 = new Object();
	//资源 2
	private static Object resource2 = new Object();
	
	public static void main(String[] args) {
		new Thread(() -> {
			synchronized (resource1) {
				System.out.println(Thread.currentThread() + "get resource1");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread() + "waiting get resource2");
				synchronized (resource2) {
					System.out.println(Thread.currentThread() + "get resource2");
				}
			}
		}, "线程 1").start();
		
		new Thread(() -> {
			synchronized (resource2) {
				System.out.println(Thread.currentThread() + "get resource2");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread() + "waiting get resource1");
				synchronized (resource1) {
					System.out.println(Thread.currentThread() + "get resource1");
				}
			}
		}, "线程 2").start();
	}
}
